<template>
  <el-card>
    <div slot="header">更换头像</div>

    <div class="pic" v-if="imgURL">
      <img :src="imgURL" alt="" />
    </div>

    <div v-else  class="avatar" @click="openSelectFile">
      请选择头像
      <input type="file" class="inputFile" accept="image/*" />
    </div>
    <el-row>
      <el-col>
        <el-button type="primary" size="mini" @click="openSelectFile" >选择图片</el-button>
        <el-button size="mini" @click="updateAvatar">上传头像</el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { updateAvatar } from '@/api/user'
export default {
  name: 'userAvatarIndex',
  data () {
    return {
      imgURL: ''
    }
  },
  methods: {
    openSelectFile () {
      // const inputFile = this.$refs['fileBox-inp']
      const input = document.querySelector('.inputFile')
      input.click()
      input.addEventListener('change', () => {
        const File = input.files[0]
        //! 直接将文件作为参数传递 不用转base64 转base64位会转化位字符串
        const reader = new FileReader()
        reader.readAsDataURL(File)
        reader.onload = () => {
          // 将base64作为src的属性传递给 imgURL
          this.imgURL = reader.result
        }
      })
    },
    updateAvatar () {
      updateAvatar({ avatar: this.imgURL }).then(res => {
        this.$message.success(res.message)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.pic {
  img {
    width: 226px;
    height: 226px;
    object-fit: contain;
  }
}
.avatar {
  width: 226px;
  height: 226px;
  background: #f5f6fa;
  border-radius: 0px 0px 2px 2px;
  font-size: 14px;
  line-height: 226px;
  text-align: center;
  color: rgba(0, 0, 0, 0.4);
  margin-bottom: 10px;
  cursor: pointer;
  .inputFile {
    display: none;
  }
}
.el-row {
  margin-left: 20px;
}
</style>
